package Exer9;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;

public class DataContainer<T> {
    private List<T> dataList;

    public DataContainer() {
        this.dataList = new ArrayList<>();
    }

    public DataContainer(List<T> initialData) {
        this.dataList = new ArrayList<>(initialData);
    }

    public void add(T element) {
        this.dataList.add(element);
    }

    public void addAll(DataContainer<? extends T> otherContainer) {
        this.dataList.addAll(otherContainer.toList());
    }

    public T get(int index) {
        if (index < 0 || index >= size()) {
            throw new IndexOutOfBoundsException(
                    String.format("索引越界：index=%d，容器大小=%d", index, size())
            );
        }
        return this.dataList.get(index);
    }

    public DataContainer<T> filter(Predicate<? super T> predicate) {
        DataContainer<T> filteredContainer = new DataContainer<>();
        for (T element : this.dataList) {
            if (predicate.test(element)) {
                filteredContainer.add(element);
            }
        }
        return filteredContainer;
    }

    public List<T> toList() {
        return new ArrayList<>(this.dataList);
    }

    public int size() {
        return this.dataList.size();
    }

    public void clear() {
        this.dataList.clear();
    }
}
